package com.haizhi.crm.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * json工具类
 * Created by ch on 2018/3/1.
 */
public class JSonUtils {

    /**
     * 将对象字段名转换为@JsonProperty设置的字段名
     *
     * @param fromObj
     * @return
     * @throws JsonProcessingException
     */
    public static Object jsonPropertyParse(Object fromObj) throws JsonProcessingException {

        String jsonStr = new ObjectMapper().writeValueAsString(fromObj);
        return JSONObject.parse(jsonStr);

    }

    /**
     * 提取Es返回数据中的data
     *
     * @param respJson
     * @return
     */
    public static List<JSONObject> getDataJsonFromESRespJson(JSONObject respJson) {

        List<JSONObject> jsonList = null;

        if (respJson == null || respJson.getIntValue("total" ) == 0) return null;

        JSONArray jsonArray = (JSONArray) respJson.get("data" );

        if (jsonArray != null && jsonArray.size() > 0) {
            jsonList = new ArrayList(jsonArray);
        }
        return jsonList;
    }


}
